#include "device_switch.h"
#include "log.h"
#include <functional>

void SwitchControl::scanCallback()
{
    for (auto it = m_keyManagerMap.begin(); it != m_keyManagerMap.end(); it++) {
        auto keyName = it->first;
        auto keyPin = m_keyPinMap[keyName];
        int keyValue = digitalRead(keyPin);  
        if(keyValue == KEY_TRIGGER_METHOD) {
            m_keyManagerMap[keyName].keyPressFlag = true;
        } else {
            if (m_keyManagerMap[keyName].keyPressFlag) {
                m_keyManagerMap[keyName].keyPressFlag = false;
                if (m_keyManagerMap[keyName].keyCallback != nullptr) {
                    m_keyManagerMap[keyName].keyCallback();
                } 
                String log = "key " + m_keyNameMap[keyName] +" press";
                LOG_INFO(log);
            }
        }
    }
    LOG_DEBUG("switch sacnning...");
}

void SwitchControl::init(void)
{
    // 初始化按键管理器
    KeyManager keyManager{};
    m_keyManagerMap[KEY_NAME::KEY_DOWN] = keyManager;
    m_keyManagerMap[KEY_NAME::KEY_UP] = keyManager;
    m_keyManagerMap[KEY_NAME::KEY_OK] = keyManager;
    // 初始化按键引脚映射
    m_keyPinMap[KEY_NAME::KEY_DOWN] = KEY_DOWN_PIN;
    m_keyPinMap[KEY_NAME::KEY_UP] = KEY_UP_PIN;
    m_keyPinMap[KEY_NAME::KEY_OK] = KEY_OK_PIN;
    // 初始化按键名称映射
    m_keyNameMap[KEY_NAME::KEY_DOWN] = "down";
    m_keyNameMap[KEY_NAME::KEY_UP] = "up";
    m_keyNameMap[KEY_NAME::KEY_OK] = "ok";
    // 创建按键扫描器
    m_switchScanner = new Ticker();
    m_switchScanner->attach_ms(SCAN_INTERVAL, [this](){ scanCallback(); });
}

void SwitchControl::setKeyCallback(KEY_NAME key_name, std::function<void()> callback)
{
    auto ret = m_keyManagerMap.find(key_name);
    if (ret != m_keyManagerMap.end()) {
        m_keyManagerMap[key_name].keyPressFlag = false;
        m_keyManagerMap[key_name].keyCallback = callback;
    }
}

SwitchControl::~SwitchControl()
{
    if (m_switchScanner != nullptr) {
        delete m_switchScanner;
    }
}